package a66weding.com.jiehuntong.fragment.category;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;

import com.andview.refreshview.XRefreshView;
import com.andview.refreshview.XRefreshViewFooter;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;

import a66weding.com.jiehuntong.R;
import a66weding.com.jiehuntong.activity.CategorySearchActivity;
import a66weding.com.jiehuntong.activity.home.hotel.shop.HomeProductdetailActivity;
import a66weding.com.jiehuntong.adapter.CategoryAdapter_Case;
import a66weding.com.jiehuntong.adapter.ProductDetailsAdapter;
import a66weding.com.jiehuntong.application.DataWareHourse;
import a66weding.com.jiehuntong.application.GlobalApplication;
import a66weding.com.jiehuntong.beans.CaseBean;
import a66weding.com.jiehuntong.beans.ErrorBean;
import a66weding.com.jiehuntong.beans.HttpRequestBean;
import a66weding.com.jiehuntong.beans.StoreDetailGuess;
import a66weding.com.jiehuntong.beans.SuccessBean;
import a66weding.com.jiehuntong.beans.User;
import a66weding.com.jiehuntong.common.api.Url;
import a66weding.com.jiehuntong.common.utils.CUtils;
import a66weding.com.jiehuntong.common.utils.SharesUtils;
import a66weding.com.jiehuntong.common.utils.Tools;
import a66weding.com.jiehuntong.http.HttpHandleUtil;
import a66weding.com.jiehuntong.http.OnNetResultListener;
import a66weding.com.jiehuntong.http.RequestCode;
import a66weding.com.jiehuntong.inner.FragmentListener;
import a66weding.com.jiehuntong.inner.OnItemClickLitener;

/**
 * Created by admin on 2016/8/5.
 * 作用：搜索商品
 */
public class CommodityFragment extends Fragment implements OnNetResultListener, OnItemClickLitener, FragmentListener {
    private View groupview;
    private RelativeLayout relativeLayout;
    private boolean isLogin;
    private User user;
    private User.DataBean userBean;
    private int memberID;
    private XRefreshView xRefreshView;
    private RecyclerView recyclerView;
    private boolean isDownRefresh = true;
    private ProductDetailsAdapter adapter;
    private int pageIndex;
    //搜索标示符
    private CategorySearchActivity categorySearchActivity;
    private String content = "";
    private List<StoreDetailGuess.DataBean> list;
    private StoreDetailGuess gussbean;

    public void initData() {
        isLogin = ((GlobalApplication) categorySearchActivity.getApplication()).isLogin();
        if (isLogin) {
            user = DataWareHourse.getInstance().getmUser();
            userBean = user.getData().get(0);
            memberID = userBean.getI_Id();
        }
        xRefreshView.setVisibility(View.INVISIBLE);
        relativeLayout.setVisibility(View.VISIBLE);
        content = SharesUtils.getInstance(getContext()).readXML("search");
        if (!TextUtils.isEmpty(content)) {
            pageIndex = 1;
            getDataNet(pageIndex);
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        categorySearchActivity = (CategorySearchActivity) getActivity();
        groupview = inflater.inflate(R.layout.fragment_package, null);
        relativeLayout = (RelativeLayout) groupview.findViewById(R.id.package_nodata);
        initRefreshView(groupview);
        if (categorySearchActivity != null) {
            categorySearchActivity.setListener(this);
        }
        initData();
        return groupview;
    }

    @Override
    public void onDestroyView() {
        if (categorySearchActivity != null) {
            categorySearchActivity.removeListener(this);
        }
        super.onDestroyView();
    }

    private void getDataNet(int page) {
        /**
         * 搜索专属 根据关键字搜索商品列表
         * GET WeddingMobileApi/get_ProductListBySearchShop?Token={Token}&pageIndex={pageIndex}&search={search}&memberID={memberID}
         */
        String word = null;
        try {
            word = URLEncoder.encode(content, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //获得memberId;
        String url = Url.GET_PRODUCTLISTBYSEARCHSHOP + "pageIndex=" + page + "&search=" + word + "&memberID=" + memberID;
        HttpRequestBean bottomListRequestBean = new HttpRequestBean(RequestCode.GETREQUEST, url, this, StoreDetailGuess.class, RequestCode.GET_PRODUCTLISTBYSEARCHSHOP);
        HttpHandleUtil.executeCommonGet(categorySearchActivity, bottomListRequestBean);
    }

    @Override
    public void onSucess(SuccessBean sucessbean) {
        Object data = sucessbean.getData();
        if (data instanceof StoreDetailGuess) {
            if (isDownRefresh) {
                xRefreshView.stopRefresh();
            } else {
                xRefreshView.stopLoadMore();
            }
            gussbean = (StoreDetailGuess) data;
            switch (gussbean.getResCode()) {
                case "0000":
                    list = gussbean.getData();
                    if (list.size() > 0) {
                        pageIndex++;
                    }
                    if (isDownRefresh) {
                        adapter.clear();
                    }
                    adapter.append(list);
                    if (adapter.getSize() == 0) {
                        relativeLayout.setVisibility(View.VISIBLE);
                        xRefreshView.setVisibility(View.INVISIBLE);
                    } else {
                        relativeLayout.setVisibility(View.INVISIBLE);
                        xRefreshView.setVisibility(View.VISIBLE);
                    }
                    break;
                default:
                    CUtils.showToast(gussbean.getMsg());
                    break;
            }
        }
    }

    @Override
    public void onError(ErrorBean errorBean) {
    }

    //初始化上啦刷新
    private void initRefreshView(View viewgroup) {
        xRefreshView = (XRefreshView) viewgroup.findViewById(R.id.category_xrefreshview);
        //是否允许下拉刷新
        xRefreshView.setPullRefreshEnable(true);
        // 设置是否可以上拉加载
        xRefreshView.setPullLoadEnable(true);
        // 设置刷新完成以后，headerview固定的时间
        xRefreshView.setPinnedTime(1000);
        // 静默加载模式不能设置footerview
        recyclerView = (RecyclerView) viewgroup.findViewById(R.id.category_recycler_view_test_rv);
        recyclerView.setHasFixedSize(true);
        //线性布局
        recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 2));
        adapter = new ProductDetailsAdapter(getActivity(), null);
        adapter.setOnItemClickLitener(this);
        recyclerView.setAdapter(adapter);
        xRefreshView.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() {
            @Override
            public void onRefresh() {
                isDownRefresh = true;
                pageIndex = 1;
                getDataNet(pageIndex);
            }

            @Override
            public void onLoadMore(boolean isSlience) {
                isDownRefresh = false;
                getDataNet(pageIndex);
            }
        });
    }

    @Override
    public void onItemClick(View view, int position) {
        // 点击进入详情界面
        Intent intent = new Intent(getActivity(), HomeProductdetailActivity.class);
        intent.putExtra("productId", list.get(position).getI_Id());
        startActivity(intent);
    }

    @Override
    public void change(String content) {
        this.content = content;
        pageIndex = 1;
        getDataNet(pageIndex);
    }
}
